package com.yuand.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuand.entity.SysRole;
import com.yuand.entity.SysUser;
import com.yuand.entity.SysUserRole;
import com.yuand.service.SysRoleService;
import com.yuand.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author yuandong
 * @since 2022-01-14
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

	@Autowired
	private SysRoleService sysRoleService;


	/**
	 * 查询用户列表
	 *
	 * @return
	 */
	@GetMapping("/list")
	public ResponseResult list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, SysRole role) {
		PageHelper.startPage(pageNum, pageSize);
		List<SysRole> roleList = sysRoleService.selectRoleList(role);
		PageInfo<SysRole> pageInfo = new PageInfo<>(roleList);
		return new ResponseResult(0, "操作成功", pageInfo);
	}


	/**
	 * 查询所有角色不分页
	 *
	 * @return
	 */
	@GetMapping("/selectAll")
	public ResponseResult selectAll() {
		List<SysRole> sysRoles = this.sysRoleService.selectAll();
		return new ResponseResult(0, sysRoles);
	}

	/**
	 * 新增角色
	 *
	 * @return
	 */
	@PostMapping("/add")
	public ResponseResult add(@RequestBody SysRole role) {
		int row = this.sysRoleService.add(role);
		if (row > 0) {
			return new ResponseResult(0, "保存成功");
		} else {
			return new ResponseResult(1, "保存失败");
		}

	}

	/**
	 * 修改角色
	 * @return
	 */
	@PostMapping("/update")
	@PreAuthorize("hasAuthority('sys:role:update')")
	public ResponseResult edit(@RequestBody SysRole role){
		int rows = this.sysRoleService.edit(role);
		if (rows > 0) {
			return new ResponseResult(0, "修改成功");
		} else {
			return new ResponseResult(1, "修改失败");
		}
	}

	/**
	 * 获取角色信息及相关联的菜单
	 *
	 * @return
	 */
	@GetMapping("/info/{roleId}")
	public ResponseResult getRoleInfo(@PathVariable Long roleId) {

		SysRole sysRole = this.sysRoleService.getRoleInfo(roleId);
		return new ResponseResult(0, "操作成功",sysRole);
	}


	/**
	 * 根据roleIds 删除角色
	 * @param roleIds
	 * @return
	 */
	@PostMapping("/del/{roleIds}")
	@PreAuthorize("hasAuthority('sys:role:del')")
	public ResponseResult del(@PathVariable  Long[] roleIds){
		this.sysRoleService.delRole(roleIds);
		return new ResponseResult(0, "操作成功");
	}


	/**
	 * 分配用户页面，取消该用户的角色关系
	 * @return
	 */
	@PostMapping("/cancelAuthUser")
	public ResponseResult cancelAuthUser(@RequestBody SysUserRole userRole){
		int flag = this.sysRoleService.cancelAuthUser(userRole);
		if(flag>0){
			return new ResponseResult(0,"操作成功");
		}else{
			return new ResponseResult(500,"操作失败");
		}

	}

}
